<template>
  <div id="box">
    <div id="capture" style="padding: 10px; background: #fff">
      <img :src="whoImg" style="width: 300px" alt="" />
      <h4 style="color: #000">Hello world!</h4>
    </div>
    <button @click="isShow()">生成海报</button>
    <button @click="nextImg()">下一张</button>
    <button @click="upImg()">上一张</button>
  </div>
  <div ref="wrapper" id="wrapper" v-show="show" @click="remove()"></div>
</template>

<script>
import html2canvas from 'html2canvas';
import { onMounted, ref } from '@vue/runtime-core';
import { Overlay } from 'vant';
export default {
  setup() {
    let imgArr = [
      {
        url: require('../assets/1.png').default
      },
      {
        url: require('../assets/2.png').default
      },
      {
        url: require('../assets/3.png').default
      },
      {
        url: require('../assets/logo.png').default
      }
    ];
    let whoImg = ref();
    let indx = ref(0);
    let show = ref(false);
    let lock = ref(1);
    let wrapper = ref();
    const isShow = () => {
      show.value = true;
      html2canvas(document.querySelector('#capture')).then((canvas) => {
        if (lock.value) {
          wrapper.value.appendChild(canvas);
          lock.value = 0;
        }
      });
    };
    const remove = () => {
      show.value = false;
      if (!lock.value) {
        lock.value = 1;
        wrapper.value.innerHTML = '';
      }
    };
    const nextImg = () => {
      if (indx.value <= 2) {
        indx.value++;
        whoImg.value = imgArr[indx.value].url;
      }
    };
    const upImg = () => {
      if (indx.value >= 1) {
        indx.value--;
        whoImg.value = imgArr[indx.value].url;
      }
    };
    onMounted(() => {
      whoImg.value = imgArr[0].url;
    });
    return {
      whoImg,
      show,
      wrapper,
      imgArr,
      nextImg,
      isShow,
      remove,
      upImg
    };
  },
  components: {
    [Overlay.name]: Overlay
  }
};
</script>

<style scoped lang="scss">
#box {
  width: 500px;
  height: 500px;
  font-size: 16px;
  img {
    width: 300px;
  }
}
#wrapper {
  width: 500px;
  height: 500px;
  position: fixed;
  top: 0;
  left: 0;
  z-index: var(--van-overlay-z-index);
  background-color: var(--van-overlay-background-color);
}
</style>
